import Web3 from "web3";
import votingArtifact from "../../build/contracts/Voting.json";

var candidates = new Map();
candidates.set("Alice", "candidate-1")
candidates.set("Bob", "candidate-2")
candidates.set("Cary", "candidate-3")

const App = {
  web3: null,
  account: null,
  voting: null,

  start: async function () {
    const { web3 } = this;

    try {
      // get contract instance
      const networkId = await web3.eth.net.getId();
      const deployedNetwork = votingArtifact.networks[networkId];
      this.voting = new web3.eth.Contract(
        votingArtifact.abi,
        deployedNetwork.address,
      );
      console.log('voting:', this.voting)
      // get accounts
      const accounts = await web3.eth.getAccounts();
      console.log('accounts', accounts);
      this.account = accounts[0];

      this.ready();
    } catch (error) {
      console.log('error', error);
      console.error("Could not connect to contract or chain.");
    }
  },

  refreshTotalVote: async function (id, name) {
    const { totalVotesFor } = this.voting.methods;
    const tickets = await totalVotesFor(name).call();
    const element = document.getElementById(id);
    element.innerHTML = tickets;
  },

  ready: async function () {

    // var candidates = {
    //   "Alice": "candidate-1",
    //   "Bob": "candidate-2",
    //   "Cary": "candidate-3",
    // }
    try {
      for (const candidate of candidates) {
        this.refreshTotalVote(candidate[1], candidate[0])
      }
    } catch (err) {
      console.err("->", err);
    }
  },

  voteForCandidate: async function () {
    try {
      const { vote } = this.voting.methods;
      const candidateName = document.getElementById("candidate").value;
      for (const candidate of candidates) {
        if (candidate[0] == candidateName) {
          let result = await vote(candidateName).send({ from: this.account });
          this.refreshTotalVote(candidate[1], candidate[0]);
        }
      }
   
    } catch (err) {
      console.error('error:', err);
    }


    // const amount = parseInt(document.getElementById("amount").value);
    // const receiver = document.getElementById("receiver").value;

    // this.setStatus("Initiating transaction... (please wait)");

    // const { sendCoin } = this.meta.methods;
    // await sendCoin(receiver, amount).send({ from: this.account });

    // this.setStatus("Transaction complete!");
    // this.refreshBalance();
  },

  // setStatus: function(message) {
  //   const status = document.getElementById("status");
  //   status.innerHTML = message;
  // },
};

window.App = App;

window.addEventListener("load", function () {
  console.log('window.ethereum', window.ethereum)
  if (window.ethereum) {
    // use MetaMask's provider
    App.web3 = new Web3(window.ethereum);
    window.ethereum.enable(); // get permission to access accounts
  } else {
    console.warn(
      "No web3 detected. Falling back to http://127.0.0.1:8545. You should remove this fallback when you deploy live",
    );
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    App.web3 = new Web3(
      new Web3.providers.HttpProvider("http://127.0.0.1:8545"),
    );
  }

  App.start();
});
